﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UI.Data;

namespace UI.Controllers
{
    public class SportCategoriesController : Controller
    {
        SPORTSALEEntities context = new SPORTSALEEntities();

        //
        // GET: /SportCategories/

        public ActionResult Index()
        {
            return View(context.Categorias);
        }

        //
        // GET: /SportCategories/Create

        public ActionResult Create()
        {
            return View(new Categorias());
        }

        //
        // POST: /SportCategories/Create

        [HttpPost]
        public ActionResult Create(Categorias sp)
        {
            try
            {
                if (context.Categorias.Any(x => x.Nombre == sp.Nombre))
                {
                    this.ModelState.AddModelError("Name", "Ese nombre ya existe!");
                    return View();
                }

                context.Categorias.AddObject(sp);
                context.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /SportCategories/Edit/5

        public ActionResult Edit(int id)
        {
            return View(context.Categorias.ToList().Where(x => x.Id == id).First());
        }

        //
        // POST: /SportCategories/Edit/5

        [HttpPost]
        public ActionResult Edit(Categorias sp)
        {
            try
            {
                Categorias old = context.Categorias.Where(x => x.Id == sp.Id).First();
                old.Nombre = sp.Nombre;
                old.Descripcion = sp.Descripcion;
          
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /SportCategories/Delete/5

        public ActionResult Delete(int id)
        {
            return View(context.Categorias.Where(x => x.Id == id).First());
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection col)
        {
            if (context.Deportes.Any(x => x.IdCategoria == id))
            {
                this.ModelState.AddModelError("ValidationSummary1", "Existen deportes con esta categoria, "
                 + "si desea eliminarla debe eliminar los deportes primero");
                return View(context.Categorias.Where(x => x.Id == id).First());
            }
            context.Categorias.DeleteObject(context.Categorias.Where(x => x.Id == id).First());
            context.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
